package com.example.gamestore.aop;

import com.alibaba.fastjson.JSON;
import com.example.gamestore.Bean.Logs;
import com.example.gamestore.Utils.HttpContextUtils;
import com.example.gamestore.Utils.IpUtils;
import com.example.gamestore.mapper.LogsMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Slf4j
@Component
public class AdminAspct {
    @Autowired
    private LogsMapper mapper;
    @Pointcut("@annotation(com.example.gamestore.aop.AdminLogAnnotation)")
    public void pt(){}

    @Around("pt()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        recordLog(point, time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AdminLogAnnotation logAnnotation = method.getAnnotation(AdminLogAnnotation.class);
        log.info("=====================log start================================");
        log.info("module:{}",logAnnotation.module());
        log.info("operation:{}",logAnnotation.operater());
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}",className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String[] argNames = signature.getParameterNames();
        String a="请求参数：";
        for(int i=0;i<args.length;i++){
            a+=argNames[i]+":="+args[i]+";";
        }
        System.out.println(a);
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}",params);

        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        log.info("ip:{}", IpUtils.getIpAddr(request));


        log.info("excute time : {} ms",time);
        Logs logs=new Logs(null,logAnnotation.module(),logAnnotation.operater(),className,methodName,a,IpUtils.getIpAddr(request),time,new Date());
        mapper.insert(logs);
        log.info("=====================log end================================");
    }
}
